package cz.anime.ppro.beans;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import cz.anime.ppro.logic.MainPageComponent;
import cz.anime.ppro.logic.UserComponent;
import cz.anime.ppro.model.Fragment;
import cz.anime.ppro.model.Webuser;

@Component
@ManagedBean
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class MainPageBean {
	
	@Autowired
	private MainPageComponent mainPageComponent;

	@Autowired
	private UserComponent userComponent;
	
	private List<Fragment> fragments;

	@PostConstruct
	public void init(){		
		fragments = new ArrayList<Fragment>();
		List<Fragment> allFragments = mainPageComponent.getFragments();
		for (Fragment fragment : allFragments) {
			List<Webuser> users = fragment.getWebusers();
			for (Webuser webuser : users) {
				if (webuser.getId() == getCurrentUserId()){
					fragments.add(fragment);
				}
			}
		}
	}

	private int getCurrentUserId(){
		return userComponent.getUserByNick(userComponent.getCurrentUsernameFromSession()).getId();
	}

	public List<Fragment> getFragments() {
		return fragments;
	}

	public void setFragments(List<Fragment> fragments) {
		this.fragments = fragments;
	}
	
}
